package com.awesome.videodemo.video.media;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.awesome.common.base.mvp.BaseActivity;
import com.awesome.common.constant.Constant;
import com.awesome.common.util.log.ShowLogUtil;
import com.awesome.videodemo.R;
import com.awesome.videodemo.video.exo.IMediaPlayerListener;
import com.awesome.videodemo.video.natives.adapter.SurfaceHolderAdapter;
import com.awesome.videodemo.util.TimeFormatUtil;

import java.io.File;

/**
 * MediaPlayer播放
 */
public class MediaPlayerActivity extends BaseActivity {
    private File mFile;
    private NativePlayer mNativePlayer;
    private SurfaceView mSurfaceView;
    private ImageView mIvPlayPause;
    private Handler mHandler;
    private SeekBar mSeekBar;
    private TextView mTvCurTime;
    private TextView mTvTotalTime;
    private final int SEEK_BAR_MAX_PROGRESS = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_player);
        initPermission();
        initView();
        initListener();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mNativePlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
//            @Override
//            public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
//                ShowLogUtil.info("width=" + width + ",height=" + height);
//                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mSurfaceView.getLayoutParams();
//                lp.height = (int) (mSurfaceView.getWidth() * 1.0f / width * height);
//                mSurfaceView.setLayoutParams(lp);
//            }
//        });
    }

    private void initView() {
        mSurfaceView = findViewById(R.id.surface_view);
        mIvPlayPause = findViewById(R.id.iv_play_pause);
        mSeekBar = findViewById(R.id.seek_bar);
        mTvCurTime = findViewById(R.id.tv_cur_time);
        mTvTotalTime = findViewById(R.id.tv_total_time);
        mSeekBar.setMax(SEEK_BAR_MAX_PROGRESS);
    }

    private void initListener() {
//        mFile = new File("/storage/emulated/0/DCIM/Camera/TG-2022-06-22-230432884.mp4");
        mFile = new File("/storage/emulated/0/DCIM/Camera/VID_20211215_113242.mp4");
        mNativePlayer = new NativePlayer(mFile.getAbsolutePath());
        mNativePlayer.setMediaPlayerListener(new IMediaPlayerListener() {
            @Override
            public void onPrepared() {
                mTvTotalTime.setText(TimeFormatUtil.INSTANCE.formatDuration(mNativePlayer.getDuration()));
            }

            @Override
            public void onError() {

            }

            @Override
            public void onComplete() {
                mSeekBar.setProgress(0);
            }

            @Override
            public void onVideoSizeChanged(int width, int height) {

            }
        });
        mIvPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mNativePlayer.isPlaying()) {
                    pause();
                } else {
                    start();
                }
            }
        });
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                long curDuration = mNativePlayer.getCurrentPosition();
                mTvCurTime.setText(TimeFormatUtil.INSTANCE.formatDuration(curDuration));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 滑动SeekBar停止时触发
                long totalDuration = mNativePlayer.getDuration();
                int progress = seekBar.getProgress();
                long curDuration = totalDuration * progress / SEEK_BAR_MAX_PROGRESS;
                mNativePlayer.seekTo(curDuration);
                start();
            }
        });
    }

    private void initData() {
        mHandler = new Handler(getMainLooper());
        initSurfaceViewMediaPlayer();
    }

    private void initPermission() {
        if (!hasPermission(Constant.WRITE_EXTERNAL_PERMISSION)) {
            requestPermission(Constant.WRITE_EXTERNAL_CODE, Constant.WRITE_EXTERNAL_PERMISSION);
        }
    }

    private void start() {
        mNativePlayer.start();
        mIvPlayPause.setSelected(true);
        startScheduleAtFixedRate();
    }

    private void pause() {
        mNativePlayer.pause();
        mIvPlayPause.setSelected(false);
        cancelScheduleAtFixedRate();
    }

    private void startScheduleAtFixedRate() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                updateProgress();
                startScheduleAtFixedRate();
            }
        }, 500);
    }

    private void cancelScheduleAtFixedRate() {
        mHandler.removeCallbacksAndMessages(null);
    }

    private void updateProgress() {
        long totalDuration = mNativePlayer.getDuration();
        long curDuration = mNativePlayer.getCurrentPosition();
        long progress = curDuration * SEEK_BAR_MAX_PROGRESS / totalDuration;
        mSeekBar.setProgress((int) progress);
    }

    private void initSurfaceViewMediaPlayer() {
        mSurfaceView.getHolder().addCallback(new SurfaceHolderAdapter() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                mNativePlayer.setDisplay(holder);
            }
        });
    }
}